package com.itheima.demo3;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @auther Macrydy
 * @date 2020/7/13 14:25
 */
public class Demo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {

        //获取字节码对象
        Class<?> clazz = Class.forName("com.itheima.demo3.Student");

        //
        //获得指定参数的构造方法
        Constructor<?> constructor = clazz.getDeclaredConstructor(String.class);
        //设置访问权限通过（暴力反射）
        constructor.setAccessible(true);
        //使用获得的构造方法创建对象
        Object zhangsan = constructor.newInstance("zhangsan");

        System.out.println(zhangsan);

        //
        Field age = clazz.getDeclaredField("age");
        age.setAccessible(true);
        age.set(zhangsan, 20);
        System.out.println(age.get(zhangsan));

        //
        Method method = clazz.getDeclaredMethod("method", String.class, int.class);
        method.setAccessible(true);
        Object invoke = method.invoke(zhangsan, "中华", 2);
        System.out.println("还剩"+invoke+"根");

    }
}
